The code behind the title page map:

lapply(c("sf", "terra", "ggplot2", "rasterVis", "gstat"), 
       library, character.only = TRUE)

# 1. Create a 50 * 50 template SpatRaster
xy_rast <- rast(
    ncols = 50, nrows = 50, xmin = 0.5, xmax = 50.5, ymin = 0.5, ymax = 50.5)

# 2. Define the gstat object and interpolate to the raster
set.seed(2)
gdummy <- gstat(
    formula = z ~ 1, locations = ~x + y, dummy = TRUE, beta = 1,
    model = vgm(psill = 0.35, range = 30, model = 'Sph'), nmax = 20)
r <- interpolate(xy_rast, gdummy, nsim = 1)

# Plot
levelplot(
    r, scales = list(draw = FALSE), axes = FALSE,  
    colorkey = list(axis.line = list(col = "#FAF0E6"), 
                    axis.text = list(col = "#FAF0E6")))

Class overview

  • Fundamentals of R (data types and objects, and basic operations)
  • R packages
  • More on Git/GitHub
  • Overview of assignment
  • Trouble shooting

A few coding tips

  • Use <- for assignment and = for passing arguments to functions.
    • This is the standard convention in R, and I expect you to follow it.
    • You may encounter R code that uses = for assignment. That is acceptable to read and understand.
  • Shortcut for <-
    • MacOS: option + -
    • Windows: Alt + -

A few coding tips

  • In R Markdown, shortcut to insert an R code chunk
    • Windows: Ctrl + Alt + I
    • MacOS: option + command + I
  • Shortcut to run selected lines
    • Windows: Ctrl + Enter
    • MacOS: command + Enter
  • Help
    • ?function
    • ??function

Fundamentals of R

Q: Why do we need to learn the fundamentals of R for working with spatial data? Hint:

  • What are the two main data types in GIS?
  • What do they look like?

Fundamentals of R

Data types

There are 6 atomic data types (or we could say classes of objects):

  • character, e.g. 'hello world', 'abc'
  • double (real or decimal), e.g. 10, 3.14, 1e10
  • integer, e.g. 1L
  • logical, e.g. TRUE, FALSE, T, F
  • complex, e.g. 1 + 3i (not commonly used by us)
  • raw (rarely used by us)

Fundamentals of R

Other special data types

  • NULL: means not exist
  • Missing data: NA. It is a special logical type, but can be convert to the specific type automatically when it is used with other data types.
  • Infinity: Inf (e.g. 1 / 0) and -Inf (e.g. -1 / 0. They are special double type.
  • Undefined value: NaN. It is also a special double type. (e.g. 0 / 0)

Fundamentals of R

Other special data types

  • Date: as.Date('1970-1-5')
  • Time: as.POSIXct('1970-1-5')
  • Factor: factor could be treated as integers with labels for categorical data. Function levels(f) can get these labels.

Fundamentals of R

Data type checking

  • typeof(x)

  • is.xxx(x):

    • e.g. is.double(x), is.integer(x), is.logical(x), is.character(x), is.complex(x), is.raw(x), is.factor

    • is.numeric(x) exams that objects behave like numbers.

    • e.g. is.na(y), is.nan(y), is.null(y), is.infinite(y), is.finite(y).

Fundamentals of R

Data type converting

  • as.xxx(x):

    • e.g. as.numeric(x), as.double(x), as.character(x), as.integer(x), as.logical(x), as.complex(x), as.raw(x), as.factor(x), as.Date(x), as.POSIXct(x).
  • logical < integer < double < character

Fundamentals of R

Vectors

  • Atomic vectors (usually refer to vector):

    • A vector is a sequence of objects of the same class.

    • Arrays and matrices are special type of vectors with dimensions.

      • Matrices have 2 dimensions.
      • Arrays could have higher dimensions.

Fundamentals of R

Vectors

  • Lists

    • Superficially for users, a list can contain objects of different classes.
    • Like vectors, a list can also be converted to list-matrix or list-array by defining dimensions.
    • data.frame and tibble are two S3 object-oriented objects that are created upon list for tabular data.

Fundamentals of R

Vectors

Fundamentals of R

Creation

  • Function vector(mode, length) can be used to initialize a vector of specific data type with defined length.
  • More commonly, function c (short for concatenate) can be used to create vectors.
  • cbind and rbind are functions can bind vectors to a matrix. Function matrix(data_vector, nrow, ncol) also can be used to create a matrix, and array(data_vector, dim) for array.
  • Anything can feed in function list to create a list, the same as data.frame.
  • is.xxx(x) and as.xxx(x) also works for vector, matrix, array, list, and data.frame.

Fundamentals of R

Atrributes

Any objects have attributes. If nothing is set, the attributes of an object is NULL. Some common attributes include:

  • names/dimnames/rownames/colnames
  • Overall length, and more specifically dim for matrix and array. Resetting dim attribute can convert a vector to matrix/array or reconstruct a matrix/array.

Practice

Create a data.frame with exactly 20 rows and 3 columns that satisfies all the conditions below. And BE CREATIVE!

  • The first column must be named “number” and contain numeric values of your choice. This column must include exactly one NA, one Inf, and one -Inf.

  • The second column must be named “letter” and contain lowercase letters (such as a, b, c, …). This column must include one NaN value.

  • The third column must be named “logical” and contain only logical values (TRUE or FALSE).

The printing results should be similar to this:

   number letter logical
15     15      o    TRUE
16     16      p   FALSE
17     17      q    TRUE
18     NA      r   FALSE
19    Inf      s    TRUE
20   -Inf    NaN   FALSE

  • I’ll leave you with a short homework to review what we’ve learned.
  • Now, let’s get back to your package.

Installing and using packages

http://r-pkgs.had.co.nz/package.html

Package structure

General common parts of a package.

Package structure

Package structure

You main tasks for the assignment package are update:

  • DESCIPTION file to incorporate updated info (e.g. your package version)
  • .R files in the R/ folder (e.g. write functions)
  • .Rmd files in the vignettes/ folder (main files for assignments)

Add a function to your package

  • Why we need functions and packages?
    • Reuse -> Reproducibility
  • Add a my_number_checker function to your package (let me show you first)
  • Add a vignette to introduce the function
    • Use usethis::use_vignette("vignette_name")
  • Update and install the package locally.
  • Git add and commit all updates.

Git branching

  • Create a new branch named test and push to the remote repo
    • git branch test (create a new branch)
    • git checkout test (switch to the new branch)
    • git push origin test (push the new branch to GitHub)
  • Have a look your remote repo on GitHub
  • Install your package from GitHub
    • In R Console, run
    devtools::install_github("your repo", build_vignettes = TRUE, 
                         auth_token = "paste_your_github_token_here")

Our Branching Model for assignments

Delete a branch

  • Delete the branch test locally and remotely
    • git checkout main (park to another branch)
    • git branch -d test (delete locally)
    • git push origin --delete test (delete remotely)

Homework

  • Write an R markdown that summarizes what we learned about the fundamentals of R.
    • Ideally in your class note folder for your own records
    • The knitted html should look like this: Expected output.
  • Post your html file in our Google Chat.
    • This counts for your participation.
  • Read the rest of Unit1-Module1 and Unit1-Module 2 (we have already covered most of the material).
  • Assignment 1 is due this Friday!
    • It is at the end of Unit1-Module1
    • Don’t worry! After today’s class, it’ll be an easy task.